package com.hosp.controller.v1;

import java.util.ArrayList;
import java.util.List;

import com.github.pagehelper.PageInfo;
import com.hosp.bean.Sysuser;
import com.hosp.controller.dto.UserDTO;
import com.hosp.service.UserService;
import com.hosp.vo.PageRequestVO;
import com.hosp.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理 API
 *
 * @author bing.zhang06@hand-china.com 2021/9/27 21:18
 **/
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 查询列表
     *
     * @param sysuser     查询条件
     * @param pageRequest 分页条件
     * @return 响应
     */
    @GetMapping("/list")
    public ResultVO<UserDTO> list(Sysuser sysuser, PageRequestVO pageRequest) {
        PageInfo<UserDTO> pageInfo = userService.list(sysuser, pageRequest);
        return new ResultVO<>(pageInfo);
    }

    /**
     * 主键查询
     *
     * @param uId 查询条件
     * @return 响应
     */
    @GetMapping("/{uId}")
    public ResultVO<UserDTO> selectById(@PathVariable("uId") Integer uId) {
        UserDTO userDTO = userService.selectById(uId);
        return new ResultVO<>(userDTO);
    }

    /**
     * 保存
     *
     * @param sysuser 保存对象
     * @return 响应
     */
    @PostMapping("/save")
    public ResultVO<String> save(Sysuser sysuser) {
        log.debug("userDTO is {}.", sysuser);

        boolean flag = userService.save(sysuser);

        if (flag) {
            return new ResultVO<>(200, "保存成功");
        } else {
            return new ResultVO<>(500, "保存失败");
        }
    }

    /**
     * 删除
     *
     * @param uIdStr 待删除 IDs
     * @return 响应
     */
    @PostMapping("/delete")
    public ResultVO<String> delete(String uIdStr) {
        List<Integer> uIds = new ArrayList<>();
        String[] split = uIdStr.split(",");
        for (String s : split) {
            uIds.add(Integer.valueOf(s));
        }
        boolean flag = userService.delete(uIds);

        if (flag) {
            return new ResultVO<>(200, "删除成功");
        } else {
            return new ResultVO<>(500, "删除失败");
        }
    }
}
